package com.hnkywl.sts.action.jhgl;

import com.google.gson.Gson;
import com.hnkywl.sts.action.flow.assign.RegectTaskSingleBackWayCmd;
import com.hnkywl.sts.entity.jhgl.Jkd;
import com.hnkywl.sts.entity.jhgl.Tpzjjhmx;
import com.hnkywl.sts.entity.jhgl.Zgzjjhmx;
import com.hnkywl.sts.entity.sys.Gncz;
import com.hnkywl.sts.service.flow.FlowService;
import com.hnkywl.sts.service.jhgl.JkdService;
import com.hnkywl.sts.service.sfgl.FkshmxService;
import com.hnkywl.sts.service.sys.GnczService;
import com.hnkywl.sts.service.sys.YgService;
import com.hnkywl.sts.util.MoneyUtils;
import net.ruixin.web.struts2.SimpleActionSupport;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.jbpm.api.*;
import org.jbpm.api.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 13-4-30
 * Time: 上午9:57
 * To change this template use File | Settings | File Templates.
 */
@Namespace("/jhgl/jkd")
public class JkdAction extends SimpleActionSupport {
    private JkdService jkdService;
    //分页组件 起始位置
    private int page;
    //分页组件 页面大小
    private int rows = 10;
    //行索引
    private int index;

    private String jkdbm;

    //供应商名称
    private String gysMc;

    private String result;

    private String taskId;

    private String content;

    private String processInstanceId;

    private String executionId;

    private FlowService flowService;

    private ProcessEngine processEngine;

    private TaskService taskService;

    private ExecutionService executionService;

    private HistoryService historyService;

    private String jkdIds;

    private Jkd jkd;

    private Long jkdId;
    //借款公司Id
    private Long jkgsId;
    //借款公司名称
    private String jkgsMc;
    //供应商Id
    private Long gysId;

    private FkshmxService fkshmxService;

    //功能操作
    private List<Gncz> gnczList;
    private GnczService gnczService;

    @Action("jkd")
    public String jkd() {
        gnczList = gnczService.findGnczByJsAndUrl(request.getServletPath());
        return SUCCESS;
    }

    //电子借款单的查询分页显示
    @Action("jkdList")
    public void jkdList() {
        this.renderJson(this.jkdService.findAllJkd(jkgsId, jkgsMc, gysMc, jkdbm, page, rows));
    }

    @Action("ytjjkdList")
    public void ytjjkdList() {
        this.renderJson(this.jkdService.findytjjkdList(gysId, page, rows));
    }

    //借款单查找付款审核明细List
    @Action("jkdsearchfkshmxList")
    public void jkdsearchfkshmxList() {
        this.renderJson(this.fkshmxService.findAllFkshmxByJkd(jkdId, page, rows));
    }


    @Action("jkdByProcessInstance")
    public void jkdByProcessInstance() {
        Jkd jkd;
        String processInstanceId = StringUtils.EMPTY;
        Execution execution = this.executionService.findExecutionById(executionId);
        if (execution != null) {
            jkd = this.jkdService.findJkdDetailByProcessInstance(execution.getProcessInstance().getId());
            processInstanceId = execution.getProcessInstance().getId();
        } else {
            jkd = this.jkdService.findJkdDetailByProcessInstance(executionId);
            processInstanceId = executionId;
        }
        String type = StringUtils.EMPTY;
        Long id = jkd.getId();
        String jkdJson = "{'id':'" + id + "','type':'" + type + "','businessNo':'" + jkd.getJkdbm() + "','processInstanceId':'" + processInstanceId + "'}";
        this.renderText(jkdJson);
    }

    @Action(value = "examineTask")
    public void examineTask() {
        if (this.result.equals("审核")) {
            Map<String, Object> var = new HashMap<String, Object>();
            var.put("owner", YgService.getCurrentYg().getId());
            var.put("opera", YgService.getCurrentYgGs() + "--" + YgService.getCurrentYgName());
            var.put("result", "审核通过");
            var.put("content", content);
            var.put("time", new Date());
            Task currentTask = this.taskService.getTask(taskId);
            String executionId = currentTask.getExecutionId();
            executionService.createVariables(executionId, var, true);

            Execution execution = this.executionService.findExecutionById(executionId);
            Jkd jkd = jkdService.findJkdDetailByProcessInstance(execution.getProcessInstance().getId());
            var.put("status", result);

            if (jkd.getCreateDepartment().getId() == 30
                    || jkd.getCreateDepartment().getId() == 26
                    || jkd.getCreateDepartment().getId() == 27
                    || jkd.getCreateDepartment().getId() == 28
                    || jkd.getCreateDepartment().getId() == 29)
                var.put("contain", StringUtils.EMPTY);
            else if (jkd.getCght() != null && jkd.getCght().getZbcg() != null && jkd.getCght().getZbcg())
                var.put("contain", "总部采购");
            else
                var.put("contain", StringUtils.EMPTY);

            this.taskService.completeTask(taskId, var);

            if (jkd.getZt().equals("ybc")) {
                jkd.setZt("ytj");
                jkdService.updateJkd(jkd);
            }
        } else {
            String result = processEngine.execute(new RegectTaskSingleBackWayCmd(taskId, content));
            if (result.equals("change")) {
                //修改状态  ytj--->ybc
                String executionId = this.historyService.createHistoryTaskQuery().taskId(taskId).uniqueResult().getExecutionId();
                Execution execution = this.executionService.findExecutionById(executionId);
                Jkd jkd = jkdService.findJkdDetailByProcessInstance(execution.getProcessInstance().getId());
                jkd.setZt("ybc");
                jkdService.updateJkd(jkd);
            }
        }
        this.renderText("{\"statusCode\":\"200\", \"message\":\"审核流程成功\"}");
    }

    @Action("commit_jkd")
    public void commitJkd() {
        try {
            Jkd jkd = this.jkdService.findJkdDetail(jkdId);
            String processName = "电子借款单流程";
            if (this.flowService.checkFlowStart(processName)) {
                String contain = StringUtils.EMPTY;
                if (jkd.getCreateDepartment().getId() == 30
                        || jkd.getCreateDepartment().getId() == 26
                        || jkd.getCreateDepartment().getId() == 27
                        || jkd.getCreateDepartment().getId() == 28
                        || jkd.getCreateDepartment().getId() == 29)
                    contain = StringUtils.EMPTY;
                else if (jkd.getCght() != null && jkd.getCght().getZbcg() != null && jkd.getCght().getZbcg())
                    contain = "总部采购";
                String processInstanceId = this.flowService.regTask(jkd.getProcessInstanceId(), processName, contain);
                jkd.setProcessInstanceId(processInstanceId);
                jkd.setZt("ytj");
            } else
                jkd.setZt("ysp");
            jkdService.saveJkd(jkd);
            renderJson("{\"statusCode\":\"200\", \"message\":\"提交借款单成功!\"}");
        } catch (Exception e) {
            e.printStackTrace();
            renderJson("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
        }
    }

    @Action("jkd_detail")
    public String jkdDetail() {
        jkd = jkdService.findJkdDetail(jkdId);
        return SUCCESS;
    }

    @Action("jkd_content")
    public String jkdContent() {
        //进入update页面
        if (jkdId != null) {
            jkd = jkdService.findJkdDetail(jkdId);
        }
        return SUCCESS;
    }

    @Action("update_jkd")
    public void updateJkd() {
        try {
            this.jkdService.updateJkd(jkd);
            renderText("{\"statusCode\":\"200\",\"message\":\"修改借款单成功！\", \"operationType\":\"update\"}");
        } catch (RuntimeException e) {
            e.printStackTrace();
            renderText("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
        }
    }

    @Action("delete_jkd")
    public void deleteJkd() {
        try {
            this.jkdService.deleteJkd(jkdId);
            renderText("{\"statusCode\":\"200\", \"message\":\"删除借款单成功！\", \"operationType\":\"delete\"}");
        } catch (Exception e) {
            e.printStackTrace();
            renderText("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
        }
    }


    //采购单打印
    @Action("jkdDetail")
    public void jkdPrintDetail() {

        Gson gson = new Gson();
        Jkd jkddetail = jkdService.findJkdDetail(jkdId);
        java.text.DecimalFormat df = new java.text.DecimalFormat("0.00");
        SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd");
        StringBuffer sbTable = new StringBuffer();
        BigDecimal je = new BigDecimal(0);
        if (null != jkddetail) {
            sbTable.append("<table class=\"tb intb\">");
            sbTable.append("<tr><td rowspan='2'>借款总金额:</td><td colspan='3'>人民币(小写)：" + df.format(jkddetail.getZfje()) + "</td><td rowspan='2' colspan='2'>借款用途:" + jkddetail.getZfkx() + "</td></tr>");
            sbTable.append("<tr><td colspan='3'>人民币(大写)：" + MoneyUtils.change(jkddetail.getZfje().doubleValue()) + "</td></tr>");
            sbTable.append("<tr><td rowspan='" + (jkddetail.getZgzjjh() != null ? (jkddetail.getZgzjjh().getZgzjjhmxList().size() + 1) : 4) + "'>付款计划</td><td>计划单号</td><td>计划付款日期</td><td>计划付款总金额</td><td>付款方式</td><td>备注</td></tr>");

            if (jkddetail.getZgzjjh() != null) {
                for (int i = 0; i < jkddetail.getZgzjjh().getZgzjjhmxList().size(); i++) {
                    Zgzjjhmx zgzjjhmx = jkddetail.getZgzjjh().getZgzjjhmxList().get(i);
                    sbTable.append("<tr>");
                    sbTable.append("<td>").append(jkddetail.getZgzjjh().getJhbh()).append("</td>");
                    sbTable.append("<td>").append(simple.format(zgzjjhmx.getFkrq())).append("</td>");
                    // sbTable.append("<td>").append(zgzjjhmx.getFkrq()).append("</td>");
                    sbTable.append("<td>").append(df.format(zgzjjhmx.getFkje())).append("</td>");
                    sbTable.append("<td></td><td></td></tr>");
                }
            } else if (jkddetail.getTpzjjh() != null) {
                for (int i = 0; i < jkddetail.getTpzjjh().getTpzjjhmxList().size(); i++) {
                    Tpzjjhmx tpzjjhmx = jkddetail.getTpzjjh().getTpzjjhmxList().get(i);
                    sbTable.append("<tr>");
                    sbTable.append("<td>").append(jkddetail.getTpzjjh().getJhbh()).append("</td>");
                    sbTable.append("<td>").append(simple.format(tpzjjhmx.getFkrq())).append("</td>");
                    //sbTable.append("<td>").append(tpzjjhmx.getFkrq()).append("</td>");
                    sbTable.append("<td>").append(df.format(tpzjjhmx.getFkje())).append("</td>");
                    sbTable.append("<td></td><td></td></tr>");
                }
            } else {
                for (int i = 0; i < 3; i++) {
                    sbTable.append("<tr>");
                    sbTable.append("<td style='height:15px'></td>");
                    sbTable.append("<td style='height:15px'></td>");
                    sbTable.append("<td style='height:15px'></td>");
                    sbTable.append("<td></td><td></td></tr>");
                }
            }
            sbTable.append("</table>");
        }
        renderHtml(sbTable.toString());
    }
    //==================get and set ================================

    public String getJkdbm() {
        return jkdbm;
    }

    public void setJkdbm(String jkdbm) {
        this.jkdbm = jkdbm;
    }

    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public int getRows() {
        return rows;
    }

    public void setRows(int rows) {
        this.rows = rows;
    }

    public int getIndex() {
        return index;
    }

    public void setIndex(int index) {
        this.index = index;
    }

    public String getResult() {
        return result;
    }

    public void setResult(String result) {
        this.result = result;
    }

    public String getTaskId() {
        return taskId;
    }

    public void setTaskId(String taskId) {
        this.taskId = taskId;
    }

    public String getProcessInstanceId() {
        return processInstanceId;
    }

    public void setProcessInstanceId(String processInstanceId) {
        this.processInstanceId = processInstanceId;
    }

    public String getExecutionId() {
        return executionId;
    }

    public void setExecutionId(String executionId) {
        this.executionId = executionId;
    }

    public String getJkdIds() {
        return jkdIds;
    }

    public void setJkdIds(String jkdIds) {
        this.jkdIds = jkdIds;
    }

    public String getContent() {
        return content;
    }

    public Jkd getJkd() {
        return jkd;
    }

    public void setJkd(Jkd jkd) {
        this.jkd = jkd;
    }

    public Long getJkdId() {
        return jkdId;
    }

    public void setJkdId(Long jkdId) {
        this.jkdId = jkdId;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getGysMc() {
        return gysMc;
    }

    public void setGysMc(String gysMc) {
        this.gysMc = gysMc;
    }

    public Long getJkgsId() {
        return jkgsId;
    }

    public void setJkgsId(Long jkgsId) {
        this.jkgsId = jkgsId;
    }

    public Long getGysId() {
        return gysId;
    }

    public void setGysId(Long gysId) {
        this.gysId = gysId;
    }

    public String getJkgsMc() {
        return jkgsMc;
    }

    public void setJkgsMc(String jkgsMc) {
        this.jkgsMc = jkgsMc;
    }

    public List<Gncz> getGnczList() {
        return gnczList;
    }

    public void setGnczList(List<Gncz> gnczList) {
        this.gnczList = gnczList;
    }

    @Autowired
    public void setGnczService(GnczService gnczService) {
        this.gnczService = gnczService;
    }

    @Autowired
    public void setFlowService(FlowService flowService) {
        this.flowService = flowService;
    }

    @Autowired
    public void setExecutionService(@Qualifier("executionService") ExecutionService executionService) {
        this.executionService = executionService;
    }

    @Autowired
    public void setTaskService(@Qualifier("taskService") TaskService taskService) {
        this.taskService = taskService;
    }

    @Autowired
    public void setProcessEngine(@Qualifier("processEngine") ProcessEngine processEngine) {
        this.processEngine = processEngine;
    }

    @Autowired
    public void setHistoryService(@Qualifier("historyService") HistoryService historyService) {
        this.historyService = historyService;
    }

    @Autowired
    public void setJkdService(JkdService jkdService) {
        this.jkdService = jkdService;
    }

    @Autowired
    public void setFkshmxService(FkshmxService fkshmxService) {
        this.fkshmxService = fkshmxService;
    }
}
